package com.shirley.netty.ssl.client;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.LineEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.util.CharsetUtil;

import java.io.InputStream;

public class SSLTcpClientChannel extends ChannelInitializer<SocketChannel> {

    private String host;
    private int port;

    public SSLTcpClientChannel(String host, int port) {
        this.host = host;
        this.port = port;
    }

    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ClassLoader classLoader = this.getClass().getClassLoader();
        InputStream x509certIs = classLoader.getResourceAsStream("server.crt");

        // In your ChannelInitializer:
        SslContext sslCtx = SslContextBuilder.forClient()
                .trustManager(x509certIs)
                .build();

        socketChannel
                .pipeline()
                .addLast(sslCtx.newHandler(socketChannel.alloc(), host, port))
                .addLast(new LineBasedFrameDecoder(1024))
                .addLast(new StringDecoder())
                .addLast(new LoggingHandler())

                .addLast(new LineEncoder(CharsetUtil.UTF_8))

                .addLast(new SSLTcpClientInputMsgHandler());
    }
}
